<?php
/**
 * beimuaihui System
 * Copyright(c) 2011-2020 beimuaihui.
 * @license    http://www.gnu.org/licenses/gpl.html     This software Under GPL V3 License 
 * beimuaihui@gmail.com
 * http://code.google.com/p/beimuaihui/
 * $Id: TranslateController.php 197 2011-02-18 12:45:33Z beimuaihui $
 * @author	$author$
 * @version $Rev$  modified time $Date$ 
 */


Loader::loadClass('json');

class Multilang_TranslateController extends Baogg_Controller_Action {

	function init() {
		global $json;
		$this->initView ();
		$this->view->baseUrl = $this->_request->getBaseUrl ();
		Zend_Loader::loadClass ( 'Translate' );
		$this->translate = new Translate ( );
		Zend_Loader::loadClass ( 'Language' );
		$this->language = new Language ( );
		Zend_Loader::loadClass ( 'DataLang' );
		$this->dataLang = new DataLang("module_permission");
	}

	/**
	 * The default action - Module list
	 */
	public function indexAction() {
		global 	$config,$multiLang;

		$this->view->config = $config;

		$session_prefix = getPageName();

		$translate_lang_id = $_SESSION["s_admin_{$session_prefix}_language_id"] ;

		$dataConfig['module_permission_id']  	= "#module_permission_id";
		$dataConfig[$multiLang->g_module_name]= "permission_name:20";
		$dataConfig[$multiLang->translate_varibles] = "varCount:10@sortable:false";
		$dataConfig[$multiLang->translate_translated_varibles] = "varCount2:10@sortable:false";
		$dataConfig[$multiLang->g_operate] = "action:10@sortable:false";

		Loader::loadClass("ext::grid");
		$grid = new extGrid("data",'','',array('multilang_content_id'),$dataConfig);

		$grid->unRegisterButton($multiLang->g_add);
		$grid->unRegisterButton($multiLang->g_edit);
		$grid->unRegisterButton($multiLang->g_del);

	//$grid->registerButton($multiLang->g_view_all,"checkLang(\""."{$config['web']['baseurl']}multilang/translate/content/?\",\"all\")",'','','view-all-icon');

		//Get Language List
		if (!$translate_lang_id ) {
			$translate_lang_id =1;
		}
		$lang_list = $this->language->getAllUnlessLang();
		if (is_array($lang_list))
		{
			foreach ((array)$lang_list as $key => $value) {
					$lang_arr[$lang_list[$key]['language_id']]=$lang_list[$key]['language_name'];
			}
			$_SESSION["s_admin_{$session_prefix}_language_id"] = (int)$lang_list[0]["language_id"];
		}

		$lang_selects = makeSelectList('language_id', $lang_arr, '',
			'class="grid_select" onchange="searchComboEvent(ext_store,this.value,\'language_id\',0,'.$grid->_limit.');" class="grid_select"', $translate_lang_id);
		$grid->registerTextBox($multiLang->g_language,$lang_selects);

		$grid->gridHeight = 400;
		$grid->checkBox=false;
		$this->view->grid = $grid;
	}

	/**
     *   Module list data
     */
	function dataAction() {
		$list = $this->translate->getList();
		echoJsonData ( $list["rs"], $list["total"] );
		$this->_helper->viewRenderer->setNoRender ();
	}


	/**
	 * The content  action - list translate contents
	 */
	public function contentAction() {
		global 	$config,$multiLang;
        checkLogin($_SESSION['s_admin_user_id']);
        checkPermission($_SESSION['s_admin_role_id']);
		$this->view->config = $config;

		$session_prefix = getPageName();
		$tran_module_permission_id=$_GET["module_permission_id"];
		$tran_language_id=$_GET["language_id"];

		//get language list
		$lang_list = $this->language->getAllByState();
		if (is_array($lang_list)) {
			foreach ((array)$lang_list as $key => $value) {
				$lang_arr[$lang_list[$key]['language_id']]=$lang_list[$key]['language_name'];
			}
			$_SESSION["s_admin_{$session_prefix}_language_id"] = (int)$lang_list[0]["language_id"];
		}
		$lang_selects = makeSelectList('language_id', $lang_arr, '', 'class="grid_select" onchange="searchComboEvent(ext_store,this.value,\'language_id\');" class="grid_select"', $translate_lang_id);

		$dataConfig['multilang_content_id']  	= "#multilang_content_id";
		$dataConfig['module_permission_id']		= "#module_permission_id";
		$dataConfig[$multiLang->g_content] = "content_en:15";
		$dataConfig[$multiLang->g_translation] = "content_tran:15";
		$dataConfig[$multiLang->translate_module_name] = "permission_name:10";
		$dataConfig[$multiLang->g_content_type]  = "content_type:10";
		$dataConfig[$multiLang->g_updated_time] = "con_updated_time:10";
		$dataConfig[$multiLang->translate_translate_date] = "tran_updated_time:10";

		Loader::loadClass("ext::grid");
		$grid = new extGrid("contentdata/?language_id={$tran_language_id}&module_permission_id={$tran_module_permission_id}",'','',array('multilang_content_id'),$dataConfig);

		$grid->unRegisterButton($multiLang->g_add);
		$grid->unRegisterButton($multiLang->g_edit);
		$grid->unRegisterButton($multiLang->g_del);
	//$grid->registerButton($multiLang->g_translate,
		$grid->getPassParam("{$grid->id}_grid","{$config['web']['baseurl']}multilang/translate/tranpage/?language_id={$tran_language_id}&module_permission_id={$tran_module_permission_id}");//,'','','translate-icon');

	//$grid->registerButton($multiLang->translate_translate_all,"translateAll();",'','','translate-all-icon');
	//$grid->registerButton($multiLang->g_back,"window.location.href='{$config['web']['baseurl']}multilang/translate/';",'','','back-icon');

		$sessionKeyword=$_SESSION["s_admin_{$session_prefix}_content"];
		$grid->registerTextBox($multiLang->g_keyword,'<input type="text" name="keyword" value="'.$sessionKeyword.'" id="keyword" onkeypress="searchEvent(ext_store,this.value,event,'.$grid->_limit.')" class="grid_search" >');

		$module_data=$this->dataLang->getDataLang( " (a.module_permission_type=0 or a.module_permission_type=1) and a.state=1", array("a.module_permission_pid asc","a.ordering desc")); 
		$module_arr['all']=$multiLang->g_all;
		$module_arr+=(array)$this->dataLang->getSelects($module_data);
		$module_selects = makeSelectList('module_permission_id_post', $module_arr, '', ' class="grid_select"  onchange="searchComboEvent(ext_store,this.value,\'module_permission_id\',0,'.$grid->_limit.');" class="grid_select" ', $tran_module_permission_id);
		$grid->registerTextBox($multiLang->translate_module_name,$module_selects);

		$grid->gridHeight = 400;
		$grid->checkBox=true;

		// to view
		$this->view->translateAllUrl="{$config['web']['baseurl']}multilang/translate/tranpage/?all=1&language_id={$tran_language_id}&module_permission_id=";
		$this->view->grid = $grid;
	}

	/** 
	 *   Content list data  action
	 */
	function contentdataAction() {
        //checkLogin($_SESSION['s_admin_user_id']);
        //checkPermission($_SESSION['s_admin_role_id']);
		$list = $this->translate->getContentList();
		echoJsonData ( $list["rs"], $list["total"] );
		$this->_helper->viewRenderer->setNoRender ();
	}

	/**
     *   Translate Page
     */
	function tranpageAction(){
		global $config,$db,$multiLang;
        checkLogin($_SESSION['s_admin_user_id']);
        checkPermission($_SESSION['s_admin_role_id']);
		$module_data=$this->dataLang->getDataLang( "a.module_permission_type=1", "");
		$module_arr=$this->dataLang->getSelects($module_data);
		$this->view->module_selects = makeSelectList('module_permission_id_post', $module_arr, '', ' class="grid_select""', $multilang_module_id);
		$this->view->contenttype_selects = makeSelectList('content_type[]',$config['global']['g_multilang_contenttype'], '', ' class="grid_select""', 1);

		$language_id=$_GET['language_id'];
		$module_permission_id_post=$_GET['module_permission_id'];
		$content_id=$_GET['multilang_content_id'];
		$this->view->language_id=$language_id;
		$this->view->module_permission_id_post=$module_permission_id_post;
		$this->view->content_id=$content_id;
		$this->view->db=$db;


		if($language_id){
			$this->view->contenttype_selects = makeSelectList('content_type[]', $config['global']['g_multilang_contenttype'], '', '', '');
			$module_data=$this->dataLang->getDataLang( "a.module_permission_type=1", "");
			$module_arr=$this->dataLang->getSelects($module_data);
			$this->view->module_selects = makeSelectList('module_permission_id_post', $module_arr, '', ' class="grid_select""', $multilang_module_id);

			if (!(empty($module_permission_id_post) || empty($language_id))){
				if ($_GET['all']=="1"){
					if ($module_permission_id_post!='all') {
						//$sql_condition=" and multilang_content.module_permission_id='{$module_permission_id_post}' ";
						if (strlen($module_permission_id_post)==3)
							$sql_condition .= " and multilang_content.module_permission_id in (select module_permission_id from module_permission where module_permission_pid ='{$module_permission_id_post}' or module_permission_id ='{$module_permission_id_post}') ";
						else
							$sql_condition .= " and multilang_content.module_permission_id= '{$module_permission_id_post}' ";
					}

					$sql = "select * from multilang_content, multilang_translate
						where  	multilang_translate.multilang_content_id=multilang_content.multilang_content_id
						and 	multilang_translate.language_id=1
						{$sql_condition} order by multilang_content.updated_time desc  ";
					//echo $sql;

				}else{
					if (is_array($content_id)){
						$cids=implode(',',$content_id);
						$sql = "select * from multilang_content, multilang_translate
							where  	multilang_translate.multilang_content_id=multilang_content.multilang_content_id
							and 	multilang_translate.language_id=1
							and   multilang_content.multilang_content_id in ({$cids}) order by multilang_content.updated_time desc  ";
					}else{
						$sql = "select * from multilang_content, multilang_translate
						where  	multilang_translate.multilang_content_id=multilang_content.multilang_content_id
						and 	multilang_translate.language_id=1
						and   multilang_content.module_permission_id='{$module_permission_id_post}' order by multilang_content.updated_time desc  ";
					}
				}
				//echo $sql;
				//exit();
				$stmt='';     $stmt=$db->query($sql);
				$this->view->rs=$stmt->fetchAll();
			}
		}

		//toolbar
		Loader::loadClass('ext::toolbar');
		$this->view->toolbarButton = new extToolBar();
		$this->view->toolbarButton->registerButton ( $multiLang->g_save, "handleForm('adminForm',\"{$config['web']['baseurl']}multilang/translate/tranaction\")", 'save-icon' );
		$this->view->toolbarButton->registerButton ( $multiLang->g_cancel, 'parent.dialog.hide()', 'cancel-icon' );
	}

	/**
     *   Translate Action
     */
	function tranactionAction(){
		global $config,$db,$multiLang;
        checkLogin($_SESSION['s_admin_user_id'],1);
        checkPermission($_SESSION['s_admin_role_id'],1);
		$var  = array();
		$var2 = array();
		$tmp1 = array();
		$tmp2 = array();
		// Edit Content
		$language_id=$_POST['language_id'];
		$module_permission_id_post=$_POST['module_permission_id_post'];
		if ($language_id && $module_permission_id_post){
			foreach ((array)$_POST['tran_content'] as $k=>$v){
				/*
				if (($_POST['content_type'][$k]==5) && (strval($_POST['comma_num'][$k])==substr_count($v,','))) {
					$commaResult[]=$_POST['variable_name'][$k];
					continue;
				}
				*/

				if ($_POST['exist_content'][$k]){
					//Update Translate
					$translate_id=$_POST['translate_id'][$k];
					$sql = "update multilang_translate set language_id={$language_id},multilang_content_id ={$k},content='{$v}',	updated_time='".date('Y-m-d H:i:s')."' ".
							" where multilang_translate_id={$translate_id};";
					$log_sql.=$sql;
				}else{
					//New Transalte
					// Check if variable name exists
					$checkSql = "select multilang_translate_id  from multilang_translate where language_id={$language_id} ".
								"and multilang_content_id ={$k}";

					$stmt='';     $stmt=$db->query($checkSql);
					$check=$stmt->fetchAll();

					if ($check[0]['multilang_translate_id']){
						// Exist
						$sql = "update multilang_translate set language_id={$language_id},multilang_content_id ={$k},content='{$v}',	updated_time='".date('Y-m-d H:i:s')."' ".
							" where multilang_translate_id={$check[0]['multilang_translate_id']};";
						$log_sql.=$sql;
					}else{
						// Not Exist. Insert it.
						if (empty($v)) {
							continue;
						}else{
							$sql=	"insert into  multilang_translate(language_id,multilang_content_id,content,updated_time) ".
								" value ({$language_id},{$k},'{$v}','".date('Y-m-d H:i:s')."'); ";
							$log_sql.=$sql;
						}

					}
				}


				$rs=$db->query($sql);
				if ($rs){
					$succResult[]=$_POST['variable_name'][$k];
				}
				else{
					$failResult[]=$_POST['variable_name'][$k];
				}

			}
		}

		if(is_array($failResult)){
			array_unique($failResult);
			$fail_str=implode(", ",$failResult);
			$msg .=$multiLang->g_save_fail." :<br >".$fail_str;
			$flag=0;
			$message="Fail to translate.";
		}else{
			$msg .=$multiLang->g_save_ok." <br >";
			$flag=1;
			$message="Succ to translate.";
		}
		echo actionMsg($flag, $msg, $fn);
		$this->_helper->viewRenderer->setNoRender ();

		$log=array();
		$log['module_permission_id'] 	= getPermissionId();
		$log['users_id']				= $_SESSION['s_admin_user_id'];
		$log['message']					= $message;
		$log['log_sql']					= $log_sql;
		$log['result']					= $flag;
		$log['log_users_id']			= $_SESSION['s_admin_user_id'];
		//print_r($log);
		insertLog($log);
	}


}
